package com.jason.reflect;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 创建一个自己的类的加载器
 * @Author: Jason
 * @Date: 16/7/29
 * @Time: 00:22
 */
public class MyClassLoader extends ClassLoader{

    // 类的名称
    // 通过读取类文件的字节码加载一个类
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> cls = null;

        try {
            String file = "/Users/hezhiyong/Desktop/com/com/abc/Dog.class";
            InputStream in = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            byte[] bt = out.toByteArray(); // 获取字节码文件
            cls = defineClass(bt, 0, bt.length);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return cls;

    }
}
